import cbApi from "../../../apis/cb/index.mjs";
import cbnApi from "../../../apis/cbn/index.mjs";

export default {
	name: "knowledge-dialog",
	props: {
		//是否显示
		visibly: {
			type: Boolean,
			default: false
		},
		//项目名称
		projectName: {
			type: String,
			default: "项目"
		},
		subjectList: {
			type: Array,
			default: () => []
		},
		//可选章节 [{subjectId:科目标识,subjectName:科目名称,chapterId:章节id,chapterName:章节名称,chapterIds:父章节id,子章节id,title:科目名称-章名称-节名称}]
		chapterList: {
			type: Array,
			default: () => []
		},
		//默认的已选知识点列表[{subjectId:科目标识,subjectName:科目名称, knowledgeId:知识点标识,knowledgeName:知识点名称,title:科目名称-知识点名称}]
		defaultData: {
			type: Array,
			default: () => []
		}
	},
	data() {
		return {
			isShow: this.visibly, // 内部的是否显示弹窗
			isLoading: false, // 加载状态
			subjectId: "", // 当前选中的科目id
			chapterIds: "", // 当前选中的章节id
			treeData: [], //章节知识点树
			cacheData: [], // 当前缓存的已选知识点列表
			expandedKeys: [], // 展开的id
			checkUpdateFun: null, // 选中节点等待加载数据后执行的缓存函数
			cacheTreeDataObj: {} // 缓存的章节知识点树，key是subjectId，value是该科目下对应的数据树，若不存在则表示还没加载过
		};
	},
	computed: {
		// 当前选中的所有章节id集合
		checkedKeys() {
			return this.cacheData.map((i) => i.knowledgeId);
		},
		// 当前可以选择的章节列表
		chapterOptionList() {
			const result = this.chapterList.reduce(
				(result, item) => {
					if (item.subjectId === this.subjectId) {
						let title = item.title.split("-");
						title.splice(0, 1);
						return [
							...result,
							{
								...item,
								title: title.join("-")
							}
						];
					}
					return result;
				},
				[{ title: "全部", chapterIds: "" }]
			);

			return result;
		}
	},
	watch: {
		// 内部和外部的变量双向绑定
		isShow(val) {
			this.$emit("update:visibly", val);
		},
		visibly(val) {
			this.isShow = val;
		}
	},
	methods: {
		// 树状懒加载处理函数
		async loadNode(node, resolve) {
			if (node.level === 1) {
				// 点击的章，查询节,因为接口直接返回了两级数据，不需要查询节的数据
				resolve(node.data.children);
			} else if (node.level === 2) {
				// 点击的节，查询知识点
				await this.updateKnowledgeTreeList(node.data.id, node.data);
				resolve(node.data.children);
				if (this.checkUpdateFun) {
					// 查询完成发现该节下无知识点，此节不可被选中，把选中状态置空
					!node.data.children.length && this.$refs.tree.setChecked(node.data.id, false);
					// 更新缓存的选中信息
					this.checkUpdateFun();
					this.checkUpdateFun = null;
				}
			} else {
				resolve([]);
			}
		},
		// 筛选函数.为了筛选章节
		filterNode(value, data) {
			if (!this.chapterIds) {
				return true;
			}
			const chapterIdArr = this.chapterIds.split(",");
			return chapterIdArr.indexOf(data.chapterId) !== -1;
		},
		// 更新章节数据
		async updateChapterTreeList() {
			if (this.cacheTreeDataObj[this.subjectId]) {
				// 如果缓存中存在，直接读取缓存数据
				this.treeData = this.cacheTreeDataObj[this.subjectId];
			} else {
				this.treeData = await new Promise((rs) => {
					this.isLoading = true;
					cbApi.queryChapterTree({
						data: {
							subjectId: this.subjectId,
							chapterLevel: 2
						},
						success: (data) => {
							const parseData = data.map((chapter1) => ({
								...chapter1,
								id: chapter1.chapterId,
								name: chapter1.chapterTitle,
								disabled: true,
								leaf: !chapter1.children || !chapter1.children.length,
								children: (chapter1.children || []).map((chapter2) => ({
									...chapter2,
									id: chapter2.chapterId,
									name: chapter2.chapterTitle
								}))
							}));
							this.cacheTreeDataObj[this.subjectId] = parseData;
							this.isLoading = false;
							rs(parseData);
						}
					});
				});
			}
			// 当前选了章节，筛选出该章节下的数据
			this.$refs.tree.filter(this.treeData);
			// 如果节的children已经存在，表示之前加载过该数据在缓存中，则展开该章和节，用于回显
			let expandedKeys = [];
			this.treeData.forEach((i1) => {
				i1.children.forEach((i2) => {
					if (i2.children) {
						// 避免重复添加章id
						if (expandedKeys.indexOf(i1.id) === -1) {
							expandedKeys.push(i1.id);
						}
						expandedKeys.push(i2.id);
					}
				});
			});
			this.expandedKeys = expandedKeys;
		},
		/**
		 * 查询知识点树状列表
		 * @param {string} 	chapterId 节id
		 * @param {object} 	node 要插入知识点的节的对象
		 * @returns {Promise} 请求的结果[]
		 */
		updateKnowledgeTreeList(chapterId, node) {
			return new Promise((rs) => {
				if (node.children) {
					rs(node.children);
					return;
				}
				this.isLoading = true;
				cbnApi.queryKnowledge({
					data: {
						chapterId
					},
					success: (data) => {
						let list = data.map((i) => ({
							...i,
							chapterId,
							children: [],
							leaf: true,
							id: i.knowledgeId,
							name: i.knowledgeTitle
						}));
						// 只展示未关联的知识点
						list = list.filter((i1) => !this.defaultData.some((i2) => i2.knowledgeId === i1.knowledgeId));
						node.children = list;
						node.disabled = !list.length;
						this.isLoading = false;
						rs(list);
					}
				});
			});
		},
		/**
		 * 切换科目
		 * @param {string} subjectId 科目id
		 */
		changeSubject(subjectId) {
			this.subjectId = subjectId;
			this.chapterIds = "";
			this.updateChapterTreeList();
		},
		/**
		 * 切换章节
		 * @param {string} chapterIds 章节id
		 */
		changeChapter(chapterIds) {
			this.chapterIds = chapterIds;
			this.updateChapterTreeList();
		},
		// 修改选中状态
		async checkChange(checkObj) {
			const fun = () => {
				let checkList = this.$refs.tree.getCheckedNodes(true);
				const otherData = this.cacheData.filter((i) => i.subjectId !== this.subjectId); // 当前存在的不属于当前科目的知识点
				const subject = this.subjectList.find((i) => i.subjectId === this.subjectId); // 当前选中的科目对象
				const nodeData = checkList.map((i) => {
					const title = subject.subjectName + "-" + i.knowledgeTitle;
					return {
						title,
						subjectName: subject.subjectName,
						subjectId: subject.subjectId,
						knowledgeId: i.knowledgeId,
						knowledgeName: i.knowledgeTitle
					};
				});
				this.cacheData = [...otherData, ...nodeData];
			};
			if (checkObj.chapterLevel === 2 && !checkObj.children) {
				// 如果当前选中的是“节”,并且该“节”下没有children属性，表示该“节”下的知识点还没加载，需要缓存处理函数，先去加载数据(loadNode)，再去执行缓存函数
				this.expandedKeys = [checkObj.id];
				this.checkUpdateFun = fun;
				return;
			}

			fun();
		},
		// 点击确定
		onSubmit() {
			this.$emit("submit", [...this.defaultData, ...this.cacheData]);
			this.isShow = false;
		}
	},
	created() {
		//科目若存在，默认选中第一个科目
		if (this.subjectList.length) {
			this.subjectId = this.subjectList[0].subjectId;
			this.updateChapterTreeList();
		}
	}
};
